package org.hscoder.springboot.elastic.film;

import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.io.FileUtils;
import org.hscoder.springboot.elastic.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class EsFilmImporter {

    public static final Logger logger = LoggerFactory.getLogger(EsFilmImporter.class);

    @Autowired
    private EsFilmRepository filmRepository;

    public int importFromLocal(String localDir) {

        List<EsFilm> esFilms = new ArrayList<>();

        for (File file : new File(localDir).listFiles()) {

            try {
                String pageContent = FileUtils.readFileToString(file, "utf-8");
                List<EsFilm> pageFilms = JsonUtil.fromJson(pageContent, new TypeReference<List<EsFilm>>() {
                });

                AtomicInteger count = new AtomicInteger();

                if (pageFilms != null) {
                    pageFilms.stream().forEach(f -> {
                        if (!StringUtils.isEmpty(f.getName())) {
                            esFilms.add(f);
                            count.incrementAndGet();
                        }
                    });
                }

                logger.info("get {}/{} records from page {}", count.get(), pageFilms != null ? pageFilms.size() : 0, file.getName());
            } catch (IOException e) {
                logger.error("read file {} failed", file.getAbsolutePath(), e);
            }

        }


        esFilms.stream().forEach(f -> {

            filmRepository.save(f);

            logger.info("import film {}", f.getName());
        });
        return esFilms.size();
    }

}
